﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Net.Sockets;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace TcpClinet
{
    public class TcpClientHelper
    {
        private TcpClient TcpClient;
        private NetworkStream _stream;

        
        public async Task<bool>  InitConnection(string ip,int port)
        {
            try
            {
                TcpClient = new TcpClient(ip, port);
                if (TcpClient.Connected)
                {
                    Console.WriteLine("连接成功");
                    return true;
                }
                else
                {
                    Console.WriteLine("连接失败");
                    return false;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"error:{ex.Message}");
                return false;
            }
            
        }


        public async Task<string> SendDataAndGetResponse(string data)
        {
            if (!TcpClient.Connected)
            {
                Console.WriteLine("没有连接到服务器");
                return null;
            }

            _stream = TcpClient.GetStream();
            byte[] byteToSend = Encoding.UTF8.GetBytes(data);
            await _stream.WriteAsync(byteToSend, 0, byteToSend.Length);
            Console.WriteLine($"发送给服务端的数据{byteToSend.ToString()}");

            // 假设服务器响应不会超过1024字节  
            byte[] buffer = new byte[1024];
            int bytesRead = _stream.Read(buffer, 0, buffer.Length);
            string response = Encoding.UTF8.GetString(buffer, 0, bytesRead);

            return response;
        }


        public async Task StartListeningAsync()
        {
            if (!TcpClient.Connected)
            {
                Console.WriteLine("Not connected to server.");
                return;
            }

            NetworkStream stream = TcpClient.GetStream();
            byte[] buffer = new byte[1024];

            try
            {
                while (true)
                {
                    int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
                    if (bytesRead == 0)
                    {
                        // 服务器关闭了连接  
                        break;
                    }

                    string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                    Console.WriteLine($"Received: {message}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error receiving data: {ex.Message}");
            }
        }
    }
}
